package com.ktwlsoft.archivemanage.controller.businessInspect;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.pinyin.PinyinUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.ktwlsoft.archivemanage.domain.business.businessService.businessInspect.BusinessInspectService;
import com.ktwlsoft.archivemanage.domain.business.businessService.businessInspect.BusinessSelfOrRepeatInspectService;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.OperationRepositoryService;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.UnitMemberRepositoryService;
import com.ktwlsoft.archivemanage.domain.dao.entity.Account;
import com.ktwlsoft.archivemanage.domain.dao.entity.OperationLog;
import com.ktwlsoft.archivemanage.domain.dao.entity.UnitMember;
import com.ktwlsoft.archivemanage.domain.dao.entity.businessInspect.BusinessInspect;
import com.ktwlsoft.archivemanage.payload.Result;
import com.ktwlsoft.archivemanage.payload.ResultType;
import com.ktwlsoft.archivemanage.payload.businessInspect.*;
import com.ktwlsoft.archivemanage.payload.guiBusiness.CommitRequest;
import com.ktwlsoft.archivemanage.payload.operationLog.SaveLogRequest;
import com.ktwlsoft.archivemanage.service.security.UserAuthenticate;
import com.ktwlsoft.archivemanage.service.security.UserPrincipal;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * 业务检查-自查复查
 *
 * @author zhuhe on 2019/11/12 15:19
 * @version 1.0
 */
@Api(value = "业务检查-自查复查", description = "业务检查-自查复查",tags = "1.2")
@RestController
@RequestMapping("businessSelfOrRepeatInspect")
@RequiredArgsConstructor
public class BusinessSelfOrRepeatInspectController {

    private final BusinessSelfOrRepeatInspectService businessInspectService;

    private final UnitMemberRepositoryService memberRepositoryService;

    /**
     * 业务检查新增 on 2019/11/6 16:55
     *
     * @param request request
     * @return ResponseEntity<?>
     */
    @ApiOperation(value = "业务检查新增", httpMethod = "POST", produces = "application/json", response = ResponseEntity.class)
    @ResponseBody
    @PostMapping("save")
    @UserAuthenticate(actionCode = "SELF_OR_REPEAT_BUSINESS_GUIDANCE_ADD")
    public ResponseEntity<?> save(@Valid @RequestBody BusinessSelfOrRepeatInspectSaveRequest request) {
        Account account = UserPrincipal.getCurrentUser();
        if (account == null) {
            account = new Account();
        }
        String name = PinyinUtil.getFirstLetter(Optional.ofNullable(account.getRealName()).orElse("xm"),"");
        List<Long> list = Lists.newArrayList();
        for(BusinessSelfOrRepeatInspectUnitRequest value:request.getUnit()){
            UnitMember unitMember = memberRepositoryService.getByUnitId(value.getUnitId());
            if(ObjectUtil.isEmpty(unitMember)){
                return ResponseEntity.ok(Result.body(null,ResultType.CHECK_ERROR).withMessage("单位为空"));
            }
            BusinessInspectSaveRequest saveRequest = BeanUtil.copyProperties(request,BusinessInspectSaveRequest.class);
            saveRequest.setUnitId(value.getUnitId());
            saveRequest.setUnitName(value.getUnitName());
            saveRequest.setUnitAddress(value.getUnitAddress());
            saveRequest.setArchivist(unitMember.getRecorder());
            saveRequest.setArchivistId(unitMember.getRecorderId());
            saveRequest.setArchivistPhone(unitMember.getRecorderTele());
            //指导单号
            String s = "";
            Result<?> mount = businessInspectService.getRecorderMount(account.getId());
            String year = DateUtil.format(new Date(), DatePattern.NORM_YEAR_PATTERN);
            String mo = ObjectUtil.isNotEmpty(mount.getData())?mount.getData().toString():"";
            String num = StrUtil.isNotBlank(mo) && !"0".equals(mo)?mo.substring(4):"000";
            String num2 = String.valueOf(Integer.parseInt(num) + 1);
            s += name;
            s += year;
            for(int i1 = num2.length();i1 < num.length();i1++){
                s += "0";
            }
            s += num2;
            saveRequest.setGuidanceNum(s);
            Result<?> result = businessInspectService.save(saveRequest,request.getInspectedBy(),request.getEntourage());
            if (result.getResultType().equals(ResultType.BUSINESS_SUCCESS)) {
                list.add(Long.parseLong(result.getData().toString()));
                saveLog(OperationLog.OperationType.ADD, (account.getRealName() != null ? account.getRealName() : "") + "为\"" + saveRequest.getUnitName() + "\"添加了业务检查,检查单号:" + saveRequest.getGuidanceNum());
            }
        }
        return ResponseEntity.ok(Result.ok(list));
    }

    /**
     * 业务检查修改 on 2019/11/7 9:10
     *
     * @param request request
     * @return ResponseEntity<?>
     */
    @ApiOperation(value = "业务检查修改", httpMethod = "POST", produces = "application/json", response = ResponseEntity.class)
    @ResponseBody
    @PostMapping("modify")
    @UserAuthenticate(actionCode = "SELF_OR_REPEAT_BUSINESS_GUIDANCE_EDIT")
    public ResponseEntity<?> modify(@Valid @RequestBody BusinessSelfOrRepeatInspectUpdateRequest request) {
        Result<?> result = businessInspectService.modify(request);
        if (result.getResultType().equals(ResultType.BUSINESS_SUCCESS)) {
            Account account = UserPrincipal.getCurrentUser();
            if (account == null) {
                account = new Account();
            }
            saveLog(OperationLog.OperationType.EDIT, (account.getRealName() != null ? account.getRealName() : "") + "编辑了\"" + request.getUnitName() + "\"的业务检查,检查单号:" + request.getGuidanceNum());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 修改检察员 on 2019/11/7 9:10
     *
     * @param request request
     * @return ResponseEntity<?>
     */
    @ApiOperation(value = "修改检察员", httpMethod = "POST", produces = "application/json", response = ResponseEntity.class)
    @ResponseBody
    @PostMapping("modifyInspectedBy")
    @UserAuthenticate(actionCode = "SELF_OR_REPEAT_BUSINESS_GUIDANCE_EDIT_INSPECTED")
    public ResponseEntity<?> modifyInspectedBy(@Valid @RequestBody BusinessSelfOrRepeatInspectUpdateInspectedByRequest request) {
        Result<?> result = businessInspectService.modifyInspectedBy(request);
        return ResponseEntity.ok(result);
    }

    /**
     * 提交 on 2020/3/12 14:44
     *
     * @param commitRequest commitRequest
     * @return ResponseEntity<?>
     */
    @ApiOperation(value = "提交")
    @ResponseBody
    @PostMapping("commit")
    @UserAuthenticate(actionCode = "COMMIT")
    public ResponseEntity<?> commit(@RequestBody CommitRequest commitRequest) {
        return ResponseEntity.ok(businessInspectService.commit(commitRequest));
    }

    /**
     * 自查 on 2019/11/7 9:10
     *
     * @param request request
     * @return ResponseEntity<?>
     */
    @ApiOperation(value = "自查", httpMethod = "POST", produces = "application/json", response = ResponseEntity.class)
    @ResponseBody
    @PostMapping("self")
    public ResponseEntity<?> self(@Valid @RequestBody BusinessSelfOrRepeatInspectUpdateRequest request) {
        request.setState(BusinessInspect.state.SELF_INSPECT_WAIT_COMMIT);
        Result<?> result = businessInspectService.modify(request);
        if (result.getResultType().equals(ResultType.BUSINESS_SUCCESS)) {
            Account account = UserPrincipal.getCurrentUser();
            if (account == null) {
                account = new Account();
            }
            saveLog(OperationLog.OperationType.EDIT, (account.getRealName() != null ? account.getRealName() : "") + "自查了\"" + request.getUnitName() + "\"的业务检查,检查单号:" + request.getGuidanceNum());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 自查提交 on 2020/3/12 14:44
     *
     * @param commitRequest commitRequest
     * @return ResponseEntity<?>
     */
    @ApiOperation(value = "自查提交")
    @ResponseBody
    @PostMapping("selfCommit")
    public ResponseEntity<?> selfCommit(@RequestBody CommitRequest commitRequest) {
        return ResponseEntity.ok(businessInspectService.selfCommit(commitRequest));
    }

    /**
     * 复查 on 2019/11/7 9:10
     *
     * @param request request
     * @return ResponseEntity<?>
     */
    @ApiOperation(value = "复查", httpMethod = "POST", produces = "application/json", response = ResponseEntity.class)
    @ResponseBody
    @PostMapping("repeat")
    @UserAuthenticate(actionCode = "SELF_OR_REPEAT_BUSINESS_REPEAT")
    public ResponseEntity<?> repeat(@Valid @RequestBody BusinessSelfOrRepeatInspectUpdateRequest request) {
        Result<?> result = businessInspectService.repeat(request);
        if (result.getResultType().equals(ResultType.BUSINESS_SUCCESS)) {
            Account account = UserPrincipal.getCurrentUser();
            if (account == null) {
                account = new Account();
            }
            saveLog(OperationLog.OperationType.EDIT, (account.getRealName() != null ? account.getRealName() : "") + "复查了\"" + request.getUnitName() + "\"的业务检查,检查单号:" + request.getGuidanceNum());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 复查提交 on 2020/3/12 14:44
     *
     * @param commitRequest commitRequest
     * @return ResponseEntity<?>
     */
    @ApiOperation(value = "复查提交")
    @ResponseBody
    @PostMapping("repeatCommit")
    @UserAuthenticate(actionCode = "REPEAT_COMMIT")
    public ResponseEntity<?> repeatCommit(@RequestBody CommitRequest commitRequest) {
        return ResponseEntity.ok(businessInspectService.repeatCommit(commitRequest));
    }

    /**
     * 业务检查撤销 on 2019/11/7 10:27
     *
     * @param id id
     * @return ResponseEntity<?>
     */
    @ApiOperation(value = "业务检查撤销", httpMethod = "GET", produces = "application/json", response = ResponseEntity.class)
    @ResponseBody
    @GetMapping("revokeById")
    @UserAuthenticate(actionCode = "SELF_OR_REPEAT_BUSINESS_GUIDANCE_CANCEL")
    public ResponseEntity<?> revokeById(@ApiParam(name = "id", value = "业务检查主键") @RequestParam(defaultValue = "") Long id) {
        Result<?> result = businessInspectService.revokeById(id);
        if (result.getResultType().equals(ResultType.BUSINESS_SUCCESS)) {
            saveLog(OperationLog.OperationType.CANCEL, "撤销业务检查,检查单号:" + result.getData());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 业务检查删除 on 2019/11/7 10:27
     *
     * @param id id
     * @return ResponseEntity<?>
     */
    @ApiOperation(value = "业务检查删除", httpMethod = "GET", produces = "application/json", response = ResponseEntity.class)
    @ResponseBody
    @GetMapping("deleteById")
    @UserAuthenticate(actionCode = "SELF_OR_REPEAT_BUSINESS_GUIDANCE_DELETE")
    public ResponseEntity<?> deleteById(@ApiParam(name = "id", value = "业务检查主键") @RequestParam(defaultValue = "") Long id) {
        Result<?> result = businessInspectService.deleteById(id);
        if (result.getResultType().equals(ResultType.BUSINESS_SUCCESS)) {
            saveLog(OperationLog.OperationType.DELETE, "删除业务检查,检查单号:" + result.getData());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 业务检查下达整改单 on 2019/11/7 10:27
     *
     * @param id id
     * @return ResponseEntity<?>
     */
    @ApiOperation(value = "业务检查下达整改单", httpMethod = "GET", produces = "application/json", response = ResponseEntity.class)
    @ResponseBody
    @GetMapping("releaseMendList")
    @UserAuthenticate(actionCode = "SELF_OR_REPEAT_BUSINESS_GUIDANCE_MEND")
    public ResponseEntity<?> releaseMendList(@ApiParam(name = "id", value = "业务检查主键") @RequestParam(defaultValue = "") Long id) {
        return ResponseEntity.ok(businessInspectService.releaseMendList(id));
    }

    /**
     * 业务检查列表 on 2019/11/7 12:06
     *
     * @return ResponseEntity<?>
     */
    @ApiOperation(value = "业务检查列表", httpMethod = "GET", produces = "application/json", response = ResponseEntity.class)
    @ResponseBody
    @GetMapping("findPage")
    @UserAuthenticate(actionCode = "SELF_OR_REPEAT_BUSINESS_GUIDANCE_LIST", skip = true)
    public ResponseEntity<?> findPage(BusinessInspectFindPageRequest request) {
        return ResponseEntity.ok(businessInspectService.findPage(request, "pc"));
    }

    /**
     * 获取业务检查详情 on 2019/11/7 10:27
     *
     * @param id id
     * @return ResponseEntity<?>
     */
    @ApiOperation(value = "获取业务检查详情", httpMethod = "GET", produces = "application/json", response = ResponseEntity.class)
    @ResponseBody
    @GetMapping("getById")
    @UserAuthenticate(actionCode = "SELF_OR_REPEAT_BUSINESS_GUIDANCE_DETAIL", skip = true)
    public ResponseEntity<?> getById(@ApiParam(name = "id", value = "业务检查主键") @RequestParam(defaultValue = "") Long id) {
        Result<?> result = businessInspectService.getById(id);
        if (result.getResultType().equals(ResultType.BUSINESS_SUCCESS)) {
            JSONObject object = JSON.parseObject(JSON.toJSONString(result.getData()));
            saveLog(OperationLog.OperationType.CHECK, "查看业务检查,检查单号:" + object.get("guidanceNum"));
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 微信业务检查列表 on 2019/11/7 12:06
     *
     * @return ResponseEntity<?>
     */
    @ApiOperation(value = "微信业务检查列表", httpMethod = "GET", produces = "application/json", response = ResponseEntity.class)
    @ResponseBody
    @GetMapping("wxFindPage")
    @UserAuthenticate(actionCode = "", skip = true)
    public ResponseEntity<?> wxFindPage(BusinessInspectFindPageRequest request) {
        return ResponseEntity.ok(businessInspectService.findPage(request, "wx"));
    }

    /**
     * 指导人列表 on 2019/11/27 11:29
     *
     * @return ResponseEntity<?>
     */
    @ApiOperation(value = "指导人列表", httpMethod = "GET", produces = "application/json", response = ResponseEntity.class)
    /*@ResponseBody*/
    @GetMapping("wxFindInstructors")
    public ResponseEntity<?> wxFindInstructors() {
        return ResponseEntity.ok(businessInspectService.FindInstructors());
    }

    /**
     * 微信获取业务检查详情 on 2019/11/7 10:27
     *
     * @param id id
     * @return ResponseEntity<?>
     */
    @ApiOperation(value = "微信获取业务检查详情", httpMethod = "GET", produces = "application/json", response = ResponseEntity.class)
    @ResponseBody
    @GetMapping("wxGetById")
    public ResponseEntity<?> wxGetById(@ApiParam(name = "id", value = "业务检查主键") @RequestParam(defaultValue = "") Long id) {
        Result<?> result = businessInspectService.getById(id);
        if (result.getResultType().equals(ResultType.BUSINESS_SUCCESS)) {
            JSONObject object = JSON.parseObject(JSON.toJSONString(result.getData()));
            saveLog(OperationLog.OperationType.CHECK, "查看业务检查,检查单号:" + object.get("guidanceNum"));
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 新增日志 on 2019/11/14 10:37
     *
     * @param operationType 操作类型
     * @param description   描述
     */
    private void saveLog(OperationLog.OperationType operationType, String description) {
        OperationRepositoryService.saveLog(new SaveLogRequest(
                operationType,
                description,
                "业务检查",
                OperationLog.BusinessType.BUSINESS
        ));
    }

    @ApiOperation(value = "获取年度所有指导单号", httpMethod = "GET", produces = "application/json", response = ResponseEntity.class)
    @ResponseBody
    @GetMapping("/getGuidNumsByYear")
    @UserAuthenticate(actionCode = "SELF_OR_REPEAT_BUSINESS_ALL_LIST", skip = true)
    public ResponseEntity<?> getGuidNumsByYear(@ApiParam(name = "createdAtFrom", value = "年度开始") @RequestParam(defaultValue = "") String createdAtFrom,
                                               @ApiParam(name = "createdAtTo", value = "年度结束") @RequestParam(defaultValue = "") String createdAtTo) {
        return ResponseEntity.ok(businessInspectService.getGuidNumsByYear(createdAtFrom, createdAtTo));
    }

    /**
     * 获取当前指导人已上报条数
     *
     * @param userId userId
     * @return ResponseEntity<?>
     */
    @ApiOperation(value = "获取当前指导人已上报条数")
    @ResponseBody
    @GetMapping("getRecorderMount")
    public ResponseEntity<?> getRecorderMount(@ApiParam(name = "userId", value = "指导员id") @RequestParam Long userId) {
        Result result = businessInspectService.getRecorderMount(userId);
        return ResponseEntity.ok(result);
    }

    /**
     * 立档单位确认
     *
     * @param request UnitConfirmRequest
     * @return ResponseEntity<?>
     */
    @ApiOperation(value = "立档单位确认")
    @ResponseBody
    @PostMapping("unitConfirm")
    public ResponseEntity<?> unitConfirm(@Valid  @RequestBody InspectConfirmRequest request) {
        return ResponseEntity.ok(businessInspectService.unitConfirm(request));
    }
}